import { GetProductPriceInfoResult } from '@/api/giga';
import { GetTemuUserInfoResult, PageQueryResult } from '@/api/temu';
import { Toaster } from '@/components/ui/sonner';
import {
  CloseTemuDialogMessage,
  ExportCorssOriginDataMessage,
  ImportCorssOriginDataMessage,
  ImportTemuSettingsMessage,
  MessageType,
  PostMessageType,
  SaveTemuSettingsMessage,
} from '@/config';
import { getGigaSkuAndProductId, getProductTotalPrice } from '@/lib/giga';
import { createButton } from '@/lib/utils';
import { useTemuStore } from '@/store/temu';
import { toast } from 'sonner';
import { iframeId, iframeWrapperId } from '.';

export default function App() {
  const appConfig = useAppConfig();
  const isDefaultOpenDialog = useTemuStore((state) => state.isDefaultOpenDialog);
  const refreshInterval = useTemuStore((state) => state.sourceInfoSettings.refreshInterval);

  // 是否默认打开对话框
  useEffect(() => {
    const timmer = setTimeout(() => {
      if (!document.location.href.includes('https://seller.kuajingmaihuo.com')) {
        return;
      }
      if (isDefaultOpenDialog) {
        const iframe = document.getElementById(iframeId) as HTMLIFrameElement;
        if (iframe) {
          iframe.contentWindow?.postMessage(
            { type: PostMessageType.openTemuDialog },
            `chrome-extension://${browser.runtime.id}/`,
          );
          const wrapper = document.getElementById(iframeWrapperId) as HTMLDivElement;
          if (wrapper) {
            wrapper.style.display = 'block';
            wrapper.style.pointerEvents = 'auto';
          }
        }
      }
    }, 1000);
    return () => {
      clearTimeout(timmer);
    };
  }, [isDefaultOpenDialog]);

  // 点击查看采集详情
  useEffect(() => {
    if (!document.location.href.includes('https://seller.kuajingmaihuo.com')) {
      return;
    }
    const id = 'enter-software';
    let infoButton: HTMLButtonElement | null = document.getElementById(
      id,
    ) as HTMLButtonElement | null;
    if (infoButton) {
      infoButton.remove();
    }
    infoButton = createButton('进入软件', 'custom-btn');
    infoButton.id = id;
    document.body.appendChild(infoButton);
    infoButton.style.cssText = 'position: fixed; top: 15px; left: 200px; z-index: 1000';
    infoButton.addEventListener('click', () => {
      const iframe = document.getElementById(iframeId) as HTMLIFrameElement;
      if (iframe) {
        iframe.contentWindow?.postMessage(
          { type: PostMessageType.openTemuDialog },
          `chrome-extension://${browser.runtime.id}/`,
        );
        const wrapper = document.getElementById(iframeWrapperId) as HTMLDivElement;
        if (wrapper) {
          wrapper.style.display = 'block';
          wrapper.style.pointerEvents = 'auto';
        }
      }
    });
  }, []);

  useEffect(() => {
    async function handleMessage(
      message: MessageEvent<
        | CloseTemuDialogMessage
        | SaveTemuSettingsMessage
        | ImportTemuSettingsMessage
        | ExportCorssOriginDataMessage
        | ImportCorssOriginDataMessage
      >,
    ) {
      console.log(message.data.type);
      if (message.data.type === PostMessageType.closeTemuDialog) {
        const wrapper = document.getElementById(iframeWrapperId) as HTMLDivElement;
        if (wrapper) {
          wrapper.style.display = 'none';
          wrapper.style.pointerEvents = 'none';
        }
      }

      if (message.data.type === PostMessageType.saveTemuSettings) {
        const { settings, suggestedName } = message.data.data;
        const settingsFileHandle = await window.showSaveFilePicker({
          id: 'settings',
          suggestedName: suggestedName || appConfig.settingsFilename,
        });
        const loadingId = toast.loading('正在导出设置');
        try {
          const writable = await settingsFileHandle.createWritable();
          await writable.write(settings);
          await writable.close();
          toast.success(`成功导出设置`);
          toast.dismiss(loadingId);
        } catch (error) {
          toast.error(`导出配置失败 ${(error as Error).message}`);
          toast.dismiss(loadingId);
        }
      }

      if (message.data.type === PostMessageType.importTemuSettings) {
        const settingsFileHandle = await window.showOpenFilePicker({
          id: 'settings',
        });
        const settingsFile = await settingsFileHandle[0].getFile();
        const settingsString = await settingsFile.text();
        message.source?.postMessage(
          {
            type: PostMessageType.sendTemuSettings,
            data: {
              settings: settingsString,
            },
          },
          {
            targetOrigin: `chrome-extension://${browser.runtime.id}/`,
          },
        );
      }

      if (message.data.type === PostMessageType.exportCorssOriginData) {
        const { data, suggestedName } = message.data.data;
        const fileHandle = await window.showSaveFilePicker({
          id: 'data',
          suggestedName: suggestedName,
        });
        const loadingId = toast.loading('正在导出数据');
        try {
          const writable = await fileHandle.createWritable();
          await writable.write(data);
          await writable.close();
          toast.success(`成功导出数据`);
          toast.dismiss(loadingId);
        } catch (error) {
          toast.error(`导出数据失败 ${(error as Error).message}`);
          toast.dismiss(loadingId);
        }
      }

      if (message.data.type === PostMessageType.importCorssOriginData) {
        const fileHandle = await window.showOpenFilePicker({
          id: 'data',
        });
        const file = await fileHandle[0].getFile();
        const dataString = await file.text();
        message.source?.postMessage(
          {
            type: PostMessageType.sendCorssOriginData,
            data: {
              data: dataString,
            },
          },
          {
            targetOrigin: `chrome-extension://${browser.runtime.id}/`,
          },
        );
      }
    }
    window.addEventListener('message', handleMessage);

    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  async function getBaseMountInfo(productId: number, mallName: string) {
    let gigaAvaliable = NaN;
    let gigaPrice = NaN;
    let temuPrice = NaN;
    let skuInfo = '';

    // 先获取 mallID
    const getTemuUserInfoResult = await browser.runtime.sendMessage({
      type: MessageType.getTemuUserInfo,
    });
    const useInfoResult = getTemuUserInfoResult.data as GetTemuUserInfoResult;

    if (getTemuUserInfoResult.code !== 0) {
      toast.error(`获取用户信息失败: ${getTemuUserInfoResult.errorMessage}`);
    }

    if (!useInfoResult.success) {
      toast.error(`获取用户信息失败: ${useInfoResult.errorMsg}`);
    }

    const mallId = useInfoResult.result.companyList[0].malInfoList.find(
      (item) => item.mallName === mallName,
    )?.mallId;

    // console.log(mallId);

    const getTemuPageQueryResult = await browser.runtime.sendMessage({
      type: MessageType.getTemuPageQuery,
      data: {
        options: {
          page: 1,
          pageSize: 1,
          productIds: [productId],
        },
        mallId: mallId,
      },
    });

    if (getTemuPageQueryResult.code !== 0) {
      toast.error(`产品数据获取失败: ${getTemuPageQueryResult.errorMessage}`);
    }

    const pageQueryResult = getTemuPageQueryResult.data as PageQueryResult;

    if (pageQueryResult.success) {
      const skuSummarie = pageQueryResult.result.pageItems[0].productSkuSummaries[0];
      skuInfo = skuSummarie.extCode;
      temuPrice = skuSummarie.siteSupplierPrices[0].supplierPrice;
      temuPrice = temuPrice / 100;
    } else {
      toast.error(`产品数据获取失败: ${pageQueryResult.errorMsg}`);
    }

    const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
    try {
      const getGigaProductPriceResult = await browser.runtime.sendMessage({
        type: MessageType.getGigaProductPrice,
        data: {
          gigaProductId,
        },
      });
      if (getGigaProductPriceResult.code === 0) {
        const result = getGigaProductPriceResult.data as GetProductPriceInfoResult;
        if (result.code === 200) {
          if (!result.data.qty_visible) {
            throw new Error(`请先登录 giga 网站`);
          }
          gigaAvaliable = result.data?.quantity?.quantity || 0;
          gigaPrice = getProductTotalPrice(result) / 100;
        }
      } else {
        throw new Error(`${getGigaProductPriceResult.errorMessage}`);
      }
    } catch (error) {
      toast.error(`${(error as Error).message}`);
    }

    return {
      gigaAvaliable,
      gigaPrice,
      temuPrice,
      skuInfo,
      gigaProductId,
    };
  }

  // 对上新生命周期管理页面进行仓库展示处理 https://agentseller.temu.com/newon/product-select
  useEffect(() => {
    const timer = setInterval(async () => {
      if (document.location.href.includes('https://agentseller.temu.com/newon/product-select')) {
        // console.log('对上新生命周期管理页面进行仓库展示处理');
        const trEles = document.querySelectorAll(
          '[class^=TB_tableWrapper_5] tbody [class^=TB_tr_5]',
        ) as NodeListOf<HTMLTableRowElement>;
        const identificationClassName = 'giga-info';
        await Promise.all(
          [...trEles].map(async (trEle) => {
            const productId = (trEle.querySelector('[class^=product-info_name]')?.textContent || '')
              .replace('SPU：', '')
              .trim();
            const mallName = document.querySelector(
              '.elli_outerWrapper_5-118-0.elli_limitWidth_5-118-0',
            )?.textContent;
            const td = trEle.querySelector('td:nth-child(3)') as HTMLTableCellElement;
            const prevWrapper = td.querySelector(
              `.${identificationClassName}`,
            ) as HTMLTableRowElement;
            if (prevWrapper) {
              // 如果产品 id 不同,应该重新生成
              if (prevWrapper.dataset.productid === productId) {
                // console.log(1231322);
                return;
              } else {
                prevWrapper.remove();
              }
            } else {
              // console.log(prevWrapper);
              td.style.setProperty('position', 'relative');
              const div = document.createElement('div');
              div.classList.add(identificationClassName);
              div.setAttribute('data-productid', productId);

              // 把 div 放第一个元素上
              td.prepend(div);

              const { temuPrice, gigaAvaliable, gigaPrice, skuInfo, gigaProductId } =
                await getBaseMountInfo(+productId, mallName!);

              div.innerHTML = `
              <span>平台: <a target="_blank" href=${`https://www.gigab2b.com/index.php?route=product/product&product_id=${gigaProductId}`}>点击跳转新连接</a></span><br />
              <span>云仓库存: ${gigaAvaliable}</span><br />
              <div>
                <span>申报价: $${temuPrice}</span><br />
                <span>成本: $${gigaPrice}</span>
              </div>
              <div>
                <span>毛利: ${(temuPrice - gigaPrice).toFixed(2)}(${(((temuPrice - gigaPrice) / gigaPrice) * 100).toFixed(2)}%)</span>
              </div>
            `;
            }
            // renderGigaInfo(trEle, identificationClassName);
          }),
        );
      }
    }, refreshInterval);
    return () => {
      clearInterval(timer);
    };
  }, [refreshInterval]);

  // 对订单页面进行处理
  useEffect(() => {
    const timer = setInterval(async () => {
      // console.log('订单页面处理');
      if (document.location.href.includes('https://agentseller-us.temu.com/mmsos/orders.html')) {
        // console.log('对上新生命周期管理页面进行仓库展示处理');
        const trEles = document.querySelectorAll(
          '.TB_tableWrapper_123 tbody tr',
        ) as NodeListOf<HTMLTableRowElement>;
        const identificationClassName = 'order-giga-info';
        // console.log('trEles', trEles);
        await Promise.all(
          [...trEles].map(async (trEle) => {
            const fourTdEle = trEle.querySelector(
              '.TB_td_123:nth-child(4)',
            ) as HTMLTableCellElement;
            const productId = (
              fourTdEle.querySelector('._1z6ZChZ-:nth-child(5) ._31FGcRdx')?.textContent || ''
            ).trim();
            const mallName = document.querySelector('.Wrz4-O9w')?.textContent?.trim();
            const prevWrapper = fourTdEle.querySelector(
              `.${identificationClassName}`,
            ) as HTMLTableRowElement;
            if (prevWrapper) {
              // 如果产品 id 不同,应该重新生成
              if (prevWrapper.dataset.productid === productId) {
                // console.log(1231322);
                return;
              } else {
                prevWrapper.remove();
              }
            } else {
              const div = document.createElement('div');
              div.classList.add(identificationClassName);
              div.setAttribute('data-productid', productId);
              // 把 div 放在第一个元素上
              fourTdEle.querySelector('._2CarhM3p')!.appendChild(div);
              const { temuPrice, gigaAvaliable, gigaPrice, skuInfo, gigaProductId } =
                await getBaseMountInfo(+productId, mallName!);

              div.innerHTML = `
              <span>平台: <a href=${`https://www.gigab2b.com/index.php?route=product/product&product_id=${gigaProductId}`}>点击跳转新连接</a></span>
              <div>
                <span>云仓库存: ${gigaAvaliable}</span>
              </div>
              <div>
                <span>申报价: $${temuPrice}</span>
              </div>
              <div>
                <span>成本: $${gigaPrice}</span>
              </div>
              <div>
                <span>毛利: ${(temuPrice - gigaPrice).toFixed(2)}(${(((temuPrice - gigaPrice) / gigaPrice) * 100).toFixed(2)}%)</span>
              </div>
            `;
            }
            // renderGigaInfo(trEle, identificationClassName);
          }),
        );
      }
    }, refreshInterval);
    return () => {
      clearInterval(timer);
    };
  }, [refreshInterval]);

  return (
    <div className="flex h-[40px] leading-[40px] items-center mr-3 cursor-pointer">
      {/* <Button>hello</Button> */}
      <Toaster className="[&_li]:p-4"></Toaster>
    </div>
  );
}
